//
//  HLShareContainerView.m
//  YueYue
//
//  Created by hulu001 on 2023/9/21.
//

#import "HLShareContainerView.h"
#import <JXCategoryView/JXCategoryView.h>
#import "HLShareCollectionView.h"
#import "HLShareRequest.h"
#import <UShareUI/UShareUI.h>
#import <UMShare/UMShare.h>

@interface HLShareContainerView ()<JXCategoryViewDelegate,JXCategoryListContainerViewDelegate>
@property (nonatomic, strong) JXCategoryTitleView *categoryView;
@property (nonatomic, strong) JXCategoryListContainerView *listContainerView;
@property (nonatomic, strong) NSArray *menus;
@property (nonatomic, strong) HLShareCollectionView *linkCollectionView;
@property (nonatomic, strong) HLShareCollectionView *posterCollectionView;

@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, strong) UILabel *shareTitleLabel;
@property (nonatomic, strong) QMUIGridView *shareButtonView;

@property (nonatomic, assign) HLShareType shareType;
@property (nonatomic, copy) HLCommonCallback callback;
@property (nonatomic, copy) HLCommonCallbackBoolBlock closeCallback;

@end

@implementation HLShareContainerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.menus = @[@"链接分享", @"海报分享"];
        [self setupView];
    }
    return self;
}



- (void)setupView
{
    self.backgroundColor = UIColorWhite;
    self.layer.cornerRadius = 12;
    self.layer.masksToBounds = YES;
    
    self.categoryView = [[JXCategoryTitleView alloc] initWithFrame:CGRectMake(0, 0, 356, 55)];
    self.categoryView.delegate = self;
    self.categoryView.titleColor = HLTextColor3;
    self.categoryView.titleSelectedColor = HLTextColor1;
    self.categoryView.cellWidthZoomEnabled = YES;
    self.categoryView.cellBackgroundSelectedColor = HLBackgroundColor;
    self.categoryView.cellBackgroundUnselectedColor = UIColorWhite;
    self.categoryView.cellSpacing = 0;
    self.categoryView.titleFont = UIFontBoldMake(18);
    self.categoryView.titleSelectedFont = UIFontBoldMake(18);
    self.categoryView.averageCellSpacingEnabled = YES;
    self.categoryView.titleColorGradientEnabled = YES;
    self.categoryView.titleLabelZoomEnabled = YES;
    self.categoryView.titleLabelZoomScale = 1.0;
    self.categoryView.backgroundColor = UIColorWhite;
    self.categoryView.titles = self.menus;
    [self addSubview:self.categoryView];
    
    self.listContainerView = [[JXCategoryListContainerView alloc] initWithType:JXCategoryListContainerType_ScrollView delegate:self];
    [self addSubview:self.listContainerView];
    [_listContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.equalTo(_categoryView.mas_bottom).offset(0);
        make.bottom.mas_equalTo(-140);
    }];
    // 关联到 categoryView
    self.categoryView.listContainer = self.listContainerView;
    
    
    self.lineView = [[UIView alloc] init];
    _lineView.backgroundColor = HLLineColor;
    [self addSubview:_lineView];
    
    self.shareTitleLabel = [[UILabel alloc] qmui_initWithFont:UIFontMediumMake(14) textColor:HLTextColor2];
    _shareTitleLabel.text = @"分享到";
    [self addSubview:_shareTitleLabel];
    [_shareTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.equalTo(_listContainerView.mas_bottom).offset(10);
    }];
    
    [_lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.centerY.equalTo(_shareTitleLabel);
        make.height.mas_equalTo(1);
    }];
    
    CGFloat width = (356) / 3;
    self.shareButtonView = [[QMUIGridView alloc] init];
    _shareButtonView.columnCount = 3;
    _shareButtonView.rowHeight = width;
    _shareButtonView.separatorWidth = 4;
    _shareButtonView.separatorColor = UIColorWhite;
    _shareButtonView.separatorDashed = NO;
    [self addSubview:_shareButtonView];
    [_shareButtonView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.height.mas_equalTo(100);
        make.top.equalTo(_shareTitleLabel.mas_bottom).offset(12);
    }];
    
    
    [self updateShareButtonWithIndex: 0];
}

- (void)updateShareButtonWithIndex:(NSInteger)index
{
    self.shareType = HLShareTypePoster;
    if (index == 0){
        self.shareType = HLShareTypeLink;
    }
    [self.shareButtonView  qmui_removeAllSubviews];
    NSArray *icons = @[@"share_wechat",@"share_pyq",@"share_copy"];
    NSArray *titles = @[@"微信",@"朋友圈",@"复制链接"];
    if (self.shareType == HLShareTypePoster){
        icons = @[@"share_wechat",@"share_pyq",@"share_copy"];
        titles = @[@"微信",@"朋友圈",@"保存图片"];
    }
    [titles enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUIButton *shareButton = [[QMUIButton alloc] init];
        [shareButton setTitle:obj forState:UIControlStateNormal];
        [shareButton setImage:UIImageMake(icons[idx]) forState:UIControlStateNormal];
        [shareButton setTitleColor:HLTextColor1 forState:UIControlStateNormal];
        [shareButton.titleLabel setFont:UIFontMediumMake(12)];
        shareButton.imagePosition = QMUIButtonImagePositionTop;
        shareButton.spacingBetweenImageAndTitle = 8;
        shareButton.tag = 100 + idx;
        [shareButton addTarget:self action:@selector(shareAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.shareButtonView addSubview:shareButton];
    }];
}


- (void)shareAction:(QMUIButton *)button
{
    UMSocialPlatformType platformType = UMSocialPlatformType_WechatSession;
    switch (button.tag) {
        case 100: // 微信
        {
            platformType = UMSocialPlatformType_WechatSession;
        }
            break;
        case 101: // 朋友圈
        {
            platformType = UMSocialPlatformType_WechatTimeLine;
        }
            break;
        case 102: // 保存图片
        {
            if (self.shareType == HLShareTypeLink){
                NSString *linkString = [self.linkCollectionView.changeModel.shareLink stringByAppendingFormat:@"?channelCode=SHARE&lang=%@&inviteCode=%@",[HLHelper systemArea],HLLoginModel.dataWithKeychain.inviteNo];
                UIPasteboard.generalPasteboard.string = linkString?:@"";
                [QMUITips showWithText:@"已复制分享链接" inView:self];
            } else {
                [self loadImageFinished:self.posterCollectionView.posterImage];
            }
            return;
        }
            break;
    }

    if (![[UMSocialManager defaultManager] isInstall:platformType]) {
        [QMUITips showWithText:@"暂未安装软件" inView:self];
        return;
    }

    if (self.shareType == HLShareTypeLink) {
        [self shareToPlatformType:platformType model:self.linkCollectionView.changeModel isLink:YES];
    } else {
        [self shareToPlatformType:platformType model:self.posterCollectionView.changeModel isLink:NO];
    }
}


- (void)shareToPlatformType:(UMSocialPlatformType)platformType model:(HLShareLinkModel *)model isLink:(BOOL)isLink
{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

    if (isLink) {
        NSString *linkString = [model.shareLink stringByAppendingFormat:@"?channelCode=SHARE&lang=%@&inviteCode=%@",[HLHelper systemLang],HLLoginModel.dataWithKeychain.inviteNo];
        //创建网页内容对象
        UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:model.title descr:model.content thumImage:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.linkImgUrl]]];
        //设置网页地址
        shareObject.webpageUrl = linkString;
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
    } else {
        UMShareImageObject *shareObject = [UMShareImageObject.alloc init];
        shareObject.shareImage = self.posterCollectionView.posterImage;
        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;
    }
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:[self qmui_viewController] completion:^(id data, NSError *error) {
        if (error) {
            NSLog(@"************Share fail with error %@*********",error.localizedDescription);

        }else{
            NSLog(@"response data is %@",data);

        }
    }];
}

#pragma mark - 海报保存

- (void)loadImageFinished:(UIImage *)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [QMUITips showWithText:@"已保存到相册" inView:self];
    } else {
        [QMUITips showWithText:error.localizedDescription];
    }
    
}


#pragma mark - JXCategoryViewDelegate


// 返回列表的数量
- (NSInteger)numberOfListsInlistContainerView:(JXCategoryListContainerView *)listContainerView {
    return self.menus.count;
}

/**
 滚动选中的情况才会调用该方法

 @param categoryView categoryView对象
 @param index 选中的index
 */
- (void)categoryView:(JXCategoryBaseView *)categoryView didScrollSelectedItemAtIndex:(NSInteger)index
{
    
    [self updateShareButtonWithIndex:index];
}

/**
 控制能否点击Item

 @param categoryView categoryView对象
 @param index 准备点击的index
 @return 能否点击
 */
- (BOOL)categoryView:(JXCategoryBaseView *)categoryView canClickItemAtIndex:(NSInteger)index
{
    [self updateShareButtonWithIndex:index];
    return  YES;
}

// 根据下标 index 返回对应遵守并实现 `JXCategoryListContentViewDelegate` 协议的列表实例
- (id<JXCategoryListContentViewDelegate>)listContainerView:(JXCategoryListContainerView *)listContainerView initListForIndex:(NSInteger)index {
    if (index == 0){
        if (self.linkCollectionView == nil){
            self.linkCollectionView = [[HLShareCollectionView alloc] initWithType:HLShareTypeLink];
        }
        return _linkCollectionView;
    } else {
        if (self.posterCollectionView == nil){
            self.posterCollectionView = [[HLShareCollectionView alloc] initWithType:HLShareTypePoster];
        }
        return _posterCollectionView;
    }
}

+ (void)showWithCallback:(HLCommonCallback)callback
{
    HLShareContainerView *containerView = [[HLShareContainerView alloc] initWithFrame:CGRectMake(0, 0, 355, 560)];
    containerView.callback = callback;
    QMUIModalPresentationViewController *modalViewController = [[QMUIModalPresentationViewController alloc] init];
    modalViewController.contentView = containerView;
    modalViewController.dimmingView.backgroundColor = [UIColorBlack colorWithAlphaComponent:0.2];
    [modalViewController showWithAnimated:YES completion:nil];
    
    containerView.closeCallback = ^(BOOL confirm) {
        if (confirm){
            [modalViewController hideWithAnimated:YES completion:nil];
        }
    };
    
}

@end
